package mq

import (
	"github.com/lishimeng/go-connector/mqtt"
	"github.com/lishimeng/go-log"
)

type Connector struct {
	Host             string
	ClientId         string
	Topic      string
	Session          *mqtt.Session
	Busy bool
}

func New(broker string, clientId string, topic string, onConnected mqtt.ConnectedCallback, onConnLost mqtt.ConnectionLostCallback) (c *Connector, err error) {

	log.Debug("create mqtt connector[%s]", broker)
	c = &Connector{
		Host:             broker,
		ClientId:         clientId,
		Topic:      topic,
	}

	c.Session = mqtt.CreateSession(false, c.ClientId, c.Host)
	c.Session.OnConnected = onConnected
	c.Session.OnLostConnect = onConnLost

	log.Debug("mqtt connect to broker %s", c.Host)
	err = c.Session.ConnectAndWait()

	return
}

func (c *Connector) Publish(payload []byte) {
	if c.Busy {
		log.Info("message busy")
		return
	}
	c.Busy = true
	go func() {
		defer func() {
			c.Busy = false
		}()
		err := c.Session.Publish(c.Topic, 0, true, payload)
		if err != nil {
			log.Info(err)
		}
	}()
}